package com.zjitc.controller;

import com.ems.KdniaoTrackQueryAPI;
import com.google.gson.Gson;
import com.zjitc.pojo.exp.Disting;
import com.zjitc.pojo.exp.ExpResult;
import com.zjitc.pojo.exp.Shipper;
import com.zjitc.pojo.Express;
import com.zjitc.vo.PageModel;
import com.zjitc.common.ServerResponse;
import com.zjitc.pojo.Caritem;
import com.zjitc.pojo.Orders;
import com.zjitc.pojo.User;
import com.zjitc.service.CarService;
import com.zjitc.service.ExpressService;
import com.zjitc.service.OrderService;
import com.zjitc.service.ProductService;
import com.ems.KdApiOrderDistinguish;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * Create By IntelliJ IDEA
 *
 * @author: myq
 * @create-Time: 2017/11/23  11:47
 */
@Controller
@RequestMapping("/order")
public class OrderController {

  @Autowired
  private OrderService service;
  @Autowired
  private CarService carService;
  @Autowired
  private ProductService pservice;
  @Autowired
  private ExpressService expressService;
  private final String USER = "user";
  private final String PAGE = "page";
  private final String ORDER = "order";
  private final String TOTAL_AMOUNT = "total_amount";
  private final String OUT_TRADE_NO = "out_trade_no";

  private static final String PAY = "pay";
  private static final String REFUND = "refund";

  /**
   * 跳转到 order_info
   */
  @RequestMapping(value = "/addOrder",method = RequestMethod.POST)
  @ResponseBody
  public ServerResponse orderinfo(HttpSession session)
      throws ServletException, IOException, InterruptedException {
    User user = (User) session.getAttribute(USER);
    List<Caritem> caritems = carService.findAll(user.getUid());

    //删除购物车数据
    if (carService.findAll(user.getUid()) != null) {
      carService.deleteAll(user.getUid());
    }
    return service.addorder(user, caritems);
  }

  /**
   * 跳转到 order_list
   */
  @RequestMapping("/orderlist")
  public ModelAndView list(HttpSession session,
      @RequestParam(value = "pageid", required = false, defaultValue = "0") Integer pageid)
      throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    User user = (User) session.getAttribute(USER);
    PageModel<Orders> orders = service.findPageByUid(user.getUid(), pageid);
    modelAndView.addObject(PAGE, orders);
    modelAndView.setViewName("jsp/order_list");
    return modelAndView;
  }

  /**
   * ########## 点击付款后————跳转到 order_info
   */
  @RequestMapping("/orderPay")
  public ModelAndView orderpay(String oid, HttpSession session)
      throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    User user = (User) session.getAttribute(USER);
    Orders order = service.findOrderFromRedis(user.getUid(), oid);
    modelAndView.addObject(ORDER, order);
    modelAndView.setViewName("jsp/order_info");
    return modelAndView;
  }

  @RequestMapping(value = "/createOrder",method = RequestMethod.POST)
  @ResponseBody
  public ServerResponse orderpayByOrder(@RequestParam("pid") String pid,
      @RequestParam("count") String count, HttpSession session) {
    User user = (User) session.getAttribute(USER);
    List<Caritem> caritems = service.createOrderitem(pid, count);
    boolean b = service.hasinventory(pid, count);
    if (b == false) {
      return ServerResponse.createError();
    }
    Orders orders = service.createOrder(caritems, user);
    session.setAttribute(ORDER, orders);
    return ServerResponse.createSuccess();
  }

  @RequestMapping("/gotoOrderInfo")
  public ModelAndView gotoOrderInfo(HttpSession session) {
    ModelAndView m = new ModelAndView("/jsp/order_info");
    Orders orders = (Orders) session.getAttribute(ORDER);
    m.addObject("order", orders);
    return m;
  }

  /**
   * ################ order_info点击确认订单后跳转到支付界面
   */
  @RequestMapping("/CompleteOrder")
  public ModelAndView complete(
      @RequestParam("oid") String oid,
      @RequestParam("address") String address,
      @RequestParam("username") String username,
      @RequestParam("phone") String phone, HttpSession session)
      throws ServletException, IOException, SQLException {
    try {
      service.judgeandupdate(session);
    } catch (TimeoutException e) {
      e.printStackTrace();
    }
    User user = (User) session.getAttribute(USER);
    ModelAndView modelAndView = new ModelAndView();
    Orders order = service.findOrderFromRedis(user.getUid(), oid);
    order.setAddress(address);
    order.setName(username);
    order.setTelephone(phone);
    service.update(user, order);
    String outTradeNo = order.getOid();
    String totalAmount = String.valueOf(order.getTotal());
    //总价
    modelAndView.addObject(TOTAL_AMOUNT, totalAmount);
    //订单编号
    modelAndView.addObject(OUT_TRADE_NO, outTradeNo);
    //alipay.trade.page.pay.jsp    outTradeNo    totalAmount
    modelAndView.setViewName("alipay.trade.page.pay");
    return modelAndView;
  }

  /**
   * ################### 支付完成后跳转回order_list
   */
  @RequestMapping("/completePay")
  public ModelAndView completepay(
      @RequestParam("out_trade_no") String oid,
      @RequestParam("trade_no") String tradeNo,
      HttpSession session
  ) throws SQLException, IOException {
    User user = (User) session.getAttribute(USER);
    Orders order = service.findOrderFromRedis(user.getUid(), oid);
    order.setState(1);
    order.setTradeNo(tradeNo);
    //修改orders数据库
    service.update(user, order);
    service.updateinventory(order.getOrderitems(), PAY);
    try {
      expressService.add(oid);
    } catch (Exception e) {
      e.printStackTrace();
    }
    ModelAndView m = new ModelAndView();
    m.setViewName("redirect:/order/orderlist.do");
    return m;
  }

  /**
   * 删除订单
   */
  @RequestMapping(value = "/orderDelete",method = RequestMethod.POST)
  @ResponseBody
  public ServerResponse delete(String oid, HttpSession session)
      throws ServletException, IOException {
    User user = (User) session.getAttribute(USER);
    return service.deleteorder(user.getUid(), oid);
  }

  @RequestMapping("/orderDeleteAll")
  public String deleteall(HttpSession session) {
    User user = (User) session.getAttribute(USER);
    int i = service.deleteAllorder(user.getUid());
    return "redirect:/order/orderlist.do";
  }

  /**
   * 取消订单/退款
   */
  @RequestMapping("/orderCancel")
  public ModelAndView cancel(
      @RequestParam(value = "WIDTRout_trade_no") String widtroutTradeNo,
      @RequestParam(value = "WIDTRrefund_amount") String widtrrefundamount,
      @RequestParam(value = "WIDTRrefund_reason") String widtrrefundReason
  ) throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("WIDTRout_trade_no", widtroutTradeNo);
    modelAndView.addObject("WIDTRrefund_amount", widtrrefundamount);
    modelAndView.addObject("WIDTRrefund_reason", widtrrefundReason);
    modelAndView.setViewName("/alipay.trade.refund");
    return modelAndView;
  }


  /**
   * 发货
   * @param oid
   * @return
   */
  @RequestMapping("shipments")
  public String shipments(String oid) {
    service.shipments(oid);
    return "redirect:/admin/adminFindAllOrder.do";
  }

  @RequestMapping("expcheck")
  public ModelAndView expcheck(String oid, HttpSession session) throws Exception {
    User user = (User) session.getAttribute(USER);
    Orders order = service.findOrderFromRedis(user.getUid(), oid);
    Express check = expressService.check(oid);
    //单号查询
    KdApiOrderDistinguish kda = new KdApiOrderDistinguish();
    String codejson = kda.getOrderTracesByJson(check.getCode());
    Gson gson = new Gson();
    Disting disting = gson.fromJson(codejson, Disting.class);
    List<Shipper> shippers = disting.getShippers();
    String expCode = "";
    Shipper shipper = null;
    for (Shipper s : shippers) {
      shipper = new Shipper(s.getShipperCode(), s.getShipperName());
    }
    expCode = shipper.getShipperCode();
    //快递即时查询
    KdniaoTrackQueryAPI kdn = new KdniaoTrackQueryAPI();
    String result = kdn.getOrderTracesByJson(expCode, check.getCode());
    ExpResult expResult = gson.fromJson(result, ExpResult.class);
    ModelAndView modelAndView = new ModelAndView("jsp/expecheck");
    modelAndView.addObject("result", expResult);
    modelAndView.addObject("shipper", shipper);
    modelAndView.addObject("check", check);
    modelAndView.addObject("order", order);
    return modelAndView;
  }

  @RequestMapping("confirm")
  public String confirm(String oid, HttpSession session) {
    User user = (User) session.getAttribute(USER);
    service.confirm(user, oid);
    return "redirect:/order/orderlist.do";
  }

  /**
   * 退款   完成
   */
  @RequestMapping("/refund")
  public ModelAndView refund(
      String msg, @RequestParam("WIDTRout_trade_no") String oid, HttpSession session)
      throws SQLException, ServletException, IOException {
    User user = (User) session.getAttribute(USER);
    String success = "Success";
    if (success.equals(msg)) {
      Orders order = service.findOrderFromRedis(user.getUid(), oid);
      order.setState(4);
      service.update(user, order);
      service.updateinventory(order.getOrderitems(), REFUND);
      msg = "退款成功";
    } else {
      msg = "退款失败";
    }
    ModelAndView modelAndView = new ModelAndView("refund");
    modelAndView.addObject("msg", msg);
    return modelAndView;
  }

}
